<template>
  <div class="app-container">
    <!-- 头部查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-col :span="12">
        <el-form-item label="订单编号" prop="orderId">
          <el-input
            v-model="queryParams.orderId"
            placeholder="请输入订单编号"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select
            v-model="queryParams.orderStatus"
            placeholder="请输入状态"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="(sta, index) in status"
              :key="index"
              :label="sta"
              :value="index"
          /></el-select>
        </el-form-item>
      </el-col>
      <el-row>
        <el-col :span="15">
          <el-form-item label="订单创建日期" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              type="datetime"
              placeholder="请选择订单创建日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              date-format="MMM DD, YYYY"
              time-format="HH:mm"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="客户" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          placeholder="请输入客户编号"
          clearable
          @click="queryPerson(0)"
        />
      </el-form-item>

      <el-form-item label="销售员编号" prop="salesId">
        <el-input
          v-model="queryParams.salesId"
          placeholder="请输入销售人员编号"
          @click="queryPerson(1)"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 头部的修改，删除 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="single"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 表格展示 -->
    <el-table
      v-loading="loading"
      :data="orders"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="销售订单编号"
        align="center"
        prop="orderId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="客户"
        align="center"
        prop="customer.customerName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="订单状态"
        align="center"
        prop="orderStatus"
        :formatter="orderStatusFormatter"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="销售人员"
        align="center"
        prop="salesPerson.userName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="销售订单送货地址"
        align="center"
        prop="shoppingAddress"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="完成时间"
        align="center"
        prop="orderDate"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="400"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="删除" placement="top">
            <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </el-tooltip>
          <el-tooltip content="查询详情" placement="top">
            <el-button
              type="text"
              icon="Search"
              @click="displayDetails(scope.row)"
              >查询详情</el-button
            >
          </el-tooltip>
          <el-tooltip
            content="修改"
            placement="top"
            v-if="scope.row.orderStatus == 0"
          >
            <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)"
              >修改</el-button
            >
          </el-tooltip>
          <el-tooltip content="退货" placement="top">
            <el-button
              type="text"
              icon="Edit"
              v-if="scope.row.orderStatus == 1"
              @click="returnTo(scope.row)"
              >退货</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页显示 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 条件查询客户,销售人员查询选择-->
    <el-dialog
      v-if="queryopen"
      :title="title"
      v-model="queryopen"
      width="800px"
      append-to-body
    >
      <el-form ref="PersonRef" :model="queryParamsPerson" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号选择" prop="id">
              <el-input
                v-model="queryParamsPerson.id"
                placeholder="请输入编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="queryParamsPerson.name"
                placeholder="请输入姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParamsPerson.status"
                placeholder="请输入状态"
                clearable
                @keyup.enter="handleQuery"
                style="width: 100%"
              >
                <el-option
                  v-for="(sta, index) in statusPerson"
                  :key="index"
                  :label="sta"
                  :value="index"
              /></el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryPerson"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQueryPerson">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="persons"
        @row-click="handleRowClick"
        :row-style="rowStyle"
      >
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column
          label="状态"
          align="center"
          prop="status"
          :formatter="personStatusFormatter"
        />
      </el-table>
      <pagination
        v-show="totalP > 0"
        :total="totalP"
        v-model:page="queryParamsPerson.pageNum"
        v-model:limit="queryParamsPerson.pageSize"
        @pagination="queryPerson(queryParamsPerson.type)"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormPerson">确 定</el-button>
          <el-button @click="cancelCheckOpen">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--订单详情展示信息弹出层-->
    <el-dialog :title="title" v-model="checkopen" width="1000px" append-to-body>
      <div>
        <!-- 表格头部 -->
        <el-row :gutter="20">
          <el-col :span="8">客户：{{ form.customer.customerName }}</el-col>
          <el-col :span="8">销售员：{{ form.salesPerson.userName }}</el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="8"
            >状态：<span style="color: green">{{
              orderStatusFormatter(form)
            }}</span></el-col
          >
          <!-- <el-col :span="8">拒绝理由：</el-col> -->
          <!-- 此处为空，所以不显示任何内容 -->
          <!-- <el-col :span="8"></el-col> -->
          <!-- 操作人、操作时间等在下方单独一行显示 -->
        </el-row>

        <el-table
          :data="form.orderDetails"
          border
          stripe
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="销售订单商品信息" align="center">
            <el-table-column
              prop="id"
              label="序号"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.productId"
              label="商品编号"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.productName"
              label="商品名称"
              width="150"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="price"
              label="商品单价"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="total"
              label="商品数量"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="totalAmount"
              label="商品总价"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.brand"
              label="商品品牌"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.description"
              label="商品描述"
              min-width="100"
              align="center"
            ></el-table-column>
          </el-table-column>
        </el-table>
        <el-row :gutter="20" style="margin-top: 10px" align="center">
          <el-col :span="12">订单总价：{{ totalMoney }}</el-col>
        </el-row>
      </div>
    </el-dialog>

    <!--订单详情展示信息修改弹出层-->
    <el-dialog v-if="open" :title="title" v-model="open" width="1000px">
      <el-form
        :model="form"
        ref="queryOrders"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="客户" prop="customerId">
          <el-input
            v-model="form.customer.customerId"
            placeholder="请输入客户编号"
            clearable
            @click="queryPerson(0)"
          />
        </el-form-item>

        <el-form-item label="销售人员编号" prop="salesId">
          <el-input
            v-model="form.salesPerson.userId"
            placeholder="请输入销售人员编号"
            style="width: 240px"
            :prefix-icon="Search"
            @click="queryPerson(1)"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select
            v-model="form.orderStatus"
            placeholder="请输入状态"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option
              v-for="(sta, index) in status2"
              :key="index"
              :label="sta"
              :value="index"
          /></el-select>
        </el-form-item>
        <el-table
          :data="form.orderDetails"
          border
          stripe
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column label="销售订单商品信息" align="center">
            <el-table-column
              prop="id"
              label="序号"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.productId"
              label="商品编号"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.productName"
              label="商品名称"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="price"
              label="商品单价"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="total"
              label="商品数量"
              width="200"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="totalAmount"
              label="商品总价"
              width="100"
              align="center"
              :formatter="totalAmountBycomputer"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.brand"
              label="商品品牌"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="inventory.product.description"
              label="商品描述"
              min-width="100"
              align="center"
            ></el-table-column>
          </el-table-column>
        </el-table>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="12">订单总价：{{ totalMoney }} </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--订单新增弹出框-->
    <el-dialog v-if="addopen" :title="title" v-model="addopen" width="1000px">
      <el-form :model="form" ref="addOrder" :inline="true" label-width="100px">
        <el-form-item label="客户编号" prop="customerId">
          <el-input
            v-model="form.customerId"
            placeholder="请输入客户编号"
            clearable
            @click="queryPerson(0)"
          />
        </el-form-item>
        <el-form-item label="销售人员编号" prop="salesId">
          <el-input
            v-model="form.salespersonId"
            placeholder="请输入销售人员编号"
            style="width: 240px"
            :prefix-icon="Search"
            @click="queryPerson(1)"
          />
        </el-form-item>
        <el-form-item label="订单地址" prop="salesId">
          <el-input
            v-model="form.shoppingAddress"
            placeholder="订单地址"
            style="width: 240px"
          />
        </el-form-item>
        <el-row>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="productAdd"
              >选择购买商品</el-button
            >
          </el-col>
        </el-row>
        <el-table
          v-if="form.orderDetails.length != 0"
          :data="form.orderDetails"
          border
          align="center"
          style="margin-top: 20px"
        >
          <el-table-column label="销售订单商品信息" align="center">
            <el-table-column
              prop="productId"
              label="商品编号"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="productName"
              label="商品名称"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="price"
              label="商品单价"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="total"
              label="商品数量"
              width="200"
              align="center"
            >
              <template #default="{ row }">
                <el-input-number
                  v-model="row.total"
                  :min="1"
                  :max="10"
                  size="small"
                  controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="totalAmount"
              label="商品总价"
              width="100"
              align="center"
              :formatter="totalAmountBycomputer"
            ></el-table-column>
          </el-table-column>
        </el-table>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="12">订单总价：{{ totalMoney }} </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormaddOrder"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品选择弹出框 -->
    <el-dialog
      v-if="productAddopen"
      :title="title"
      v-model="productAddopen"
      width="800px"
      append-to-body
    >
      <el-form ref="ProductRef" :model="queryproduct" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号选择" prop="productId">
              <el-input
                v-model="queryproduct.productId"
                placeholder="请输入编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model="queryproduct.productName"
                placeholder="请输入姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品品牌" prop="brand">
              <el-input
                v-model="queryproduct.brand"
                placeholder="请输入商品品牌"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQueryProduct"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQueryPerson">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="products"
        @row-click="handleRowClick"
        :row-style="rowStyle"
      >
        <el-table-column
          label="编号"
          align="center"
          prop="productId"
          width="50px"
        />
        <el-table-column
          label="商品名称"
          align="center"
          prop="productName"
          width="100px"
        />
        <el-table-column
          label="品牌"
          align="center"
          prop="brand"
          width="100px"
        />
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column
          label="商品库存"
          align="center"
          width="100px"
          prop="inventoryQuantity"
        />
        <el-table-column
          label="商品价格"
          align="center"
          width="100px"
          prop="price"
        />
        <el-table-column label="商品数量" align="center" width="200px">
          <template #default="{ row }">
            <el-row>
              商品数量：<el-input-number
                v-model="row.total"
                :min="0"
                :max="100"
                size="small"
                controls-position="right"
              />
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="totalPro > 0"
        :total="totalPro"
        v-model:page="queryproduct.pageNum"
        v-model:limit="queryproduct.pageSize"
        @pagination="handleQueryProduct"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormProduct">确 定</el-button>
          <el-button @click="cancelProOpen">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--退货弹出层-->
    <el-dialog
      v-if="returnOpen"
      :title="title"
      v-model="returnOpen"
      width="1000px"
    >
      <el-form
        :model="returnForm"
        ref="queryOrders"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="returnForm.orderId" disable="true" />
        </el-form-item>
        <el-form-item label="退货原因" prop="rtvBecause">
          <el-input
            v-model="returnForm.rtvBecause"
            placeholder="请输入退货原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="returnSub">确 定</el-button>
          <el-button @click="cancelReturn">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import {
  addOrder,
  addReturn,
  delOrder,
  getCus,
  getOrder,
  getProducts,
  getSalesPerson,
  listOrder,
  updateOrder,
} from "@/api/sale/order.js";

// const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_job_group, sys_job_status } = proxy.useDict(
//   "sys_job_group",
//   "sys_job_status"
// );

const orders = ref([]);
const persons = ref([]);
const customer = ref([]);
const customerAll = ref([]);
const products = ref([]);
const status = ref(["未发货", "已完成", "退货"]);
const status2 = ref(["未发货", "已完成"]);
const statusPerson = ref(["启用", "失效"]);
const returnOpen = ref(false);
const open = ref(false);
const checkopen = ref(false);
const addopen = ref(false);
const productAddopen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const totalP = ref(0);
const totalPro = ref(0);
const selectedId = ref(null);
const title = ref("");
const queryopen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    orderId: undefined,
    orderStatus: undefined,
    createTime: undefined,
    customerId: undefined,
    salesId: undefined,
  },
  rules: {},
  queryParamsPerson: {
    type: undefined,
    pageNum: 1,
    pageSize: 5,
    id: undefined,
    name: undefined,
    status: undefined,
  },
  queryproduct: {
    pageNum: 1,
    pageSize: 5,
    productId: undefined,
    productName: undefined,
    brand: undefined,
  },
  returnForm: {
    orderId: undefined,
    rtvBecause: undefined,
    rtvStatus: 0,
  },
});

const {
  queryParams,
  form,
  rules,
  queryParamsPerson,
  queryproduct,
  returnForm,
} = toRefs(data);
//状态展示文字加工
function orderStatusFormatter(row) {
  // 确保 orderStatus 是有效的索引
  if (row.orderStatus !== undefined && row.orderStatus < status.value.length) {
    return status.value[row.orderStatus];
  }
  return ""; // 或者返回一个默认值
}

//状态展示文字加工
function personStatusFormatter(row) {
  // 确保 orderStatus 是有效的索引
  if (row.status !== undefined && row.status < statusPerson.value.length) {
    return statusPerson.value[row.status];
  }
  return ""; // 或者返回一个默认值
}

//总金额计算
const totalMoney = computed(() => {
  return form.value.orderDetails.reduce((total, detail) => {
    return total + detail.total * detail.price;
  }, 0);
});

const totalMoneyPro = computed(() => {
  return products.value.reduce((total, detail) => {
    return total + detail.total * detail.unitPurchasePrice;
  }, 0);
});

/** 查询定时任务列表 */
function getList() {
  loading.value = true;
  console.log(queryParams.value);
  listOrder(queryParams.value).then((response) => {
    console.log(response);
    loading.value = false;
    if (response.meta.status == 200) {
      orders.value = response.data.list;
      total.value = response.data.total;
    } else {
      orders.value = null;
      total.value = 0;
    }
  });
}

function queryPerson(person) {
  if (person == 0 || queryParamsPerson.type == 0) {
    queryParamsPerson.value.type = 0;
    //客户人员查询请求数据
    getCus(queryParamsPerson.value).then((response) => {
      if (response.meta.status == 200) {
        //客户数据获取回调
        queryopen.value = true;
        title.value = "选择客户信息";
        totalP.value = response.data.total;
        persons.value = [];
        response.data.records.forEach((element) => {
          let form = {
            id: element.customerId,
            name: element.customerName,
            status: element.status,
          };
          persons.value.push(form);
        });
        console.log(persons.value);
      }
    });
  } else {
    queryParamsPerson.value.type = 1;
    //销售人员查询请求
    getSalesPerson(queryParamsPerson.value).then((response) => {
      //销售人员数据获取回调
      console.log(response);
      queryopen.value = true;
      totalP.value = response.data.total;
      title.value = "选择销售人员信息";
      persons.value = [];
      response.data.records.forEach((element) => {
        let form = {
          id: element.userId,
          name: element.userName,
          status: element.status,
        };
        persons.value.push(form);
      });
      console.log(persons.value);
    });
  }
}
function handleRowClick(row) {
  selectedId.value = row.id; // 更新选中行的 id
  queryParamsPerson.value.id = row.id;
  queryParamsPerson.value.name = row.name;
  queryParamsPerson.value.status = row.status;
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
  if (addopen.value == true) {
    addopen.value = false;
  }
}
/** 人员确认取消按钮 */
function cancelCheckOpen() {
  queryopen.value = false;
  resetCheck();
}
/** 商品选择确认取消按钮 */
function cancelProOpen() {
  productAddopen.value = false;
  returnForm.value = {
    orderId: undefined,
    rtvBecause: undefined,
    rtvStatus: 0,
  };
}

/** 退货确认取消按钮 */
function cancelReturn() {
  returnOpen.value = false;
  resetPro();
}
/** 商品确认条件重置 */
function resetPro() {
  (queryproduct.value = {
    pageNum: 1,
    pageSize: 5,
    productId: undefined,
    productName: undefined,
    brand: undefined,
  }),
    proxy.resetForm("ProductRef");
}
/** 人员确认条件重置 */
function resetCheck() {
  queryParamsPerson.value = {
    pageNum: 1,
    pageSize: 5,
    type: undefined,
    id: undefined,
    name: undefined,
    status: 0,
  };
  proxy.resetForm("PersonRef");
}
/** 表单重置 */
function reset() {
  form.value = {
    orderId: undefined,
    orderStatus: undefined,
    createTime: undefined,
    customerId: undefined,
    salesId: undefined,
    concurrent: 1,
    status: "0",
  };
  proxy.resetForm("jobRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function resetQueryPerson() {
  proxy.resetForm("PersonRef");
  handleQueryPerson();
}

function handleQueryPerson() {
  queryParamsPerson.value.pageNum = 1;
  queryPerson(queryParamsPerson.value.type);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = {};
  const orderId = row.orderId || ids.value;
  getOrder(orderId).then((response) => {
    console.log(response.data);
    form.value = response.data;
    open.value = true;
    title.value = "修改销售订单消息";
  });
}

/** 查询订单详情按钮操作 */
function displayDetails(row) {
  reset();
  form.value = {};
  const orderId = row.orderId || ids.value;
  getOrder(orderId).then((response) => {
    form.value = response.data;
    checkopen.value = true;
    title.value = "订单详情";
  });
}

/** 提交按钮 */
function submitForm() {
  if (title.value == "修改销售订单消息") {
    updateOrder(form.value).then((response) => {
      response.meta.code == 204;
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList();
    });
  } else {
    addOrder(form.value).then((response) => {
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
    });
  }
}

/** 人员信息展示弹出框信息确认 */
function submitFormPerson() {
  proxy.$refs["PersonRef"].validate((valid) => {
    if (valid) {
      if (selectedId.value != 0) {
        if (title.value == "选择销售人员信息") {
          if (open.value == true) {
            form.value.salesPerson.userId = selectedId.value;
            form.value.salespersonId = selectedId.value;
          } else if (addopen.value == true) {
            form.value.salespersonId = selectedId.value;
          } else {
            queryParams.value.salesId = selectedId.value;
          }
        } else {
          if (open.value == true) {
            form.value.customer.customerId = selectedId.value;
            form.value.customerId = selectedId.value;
          } else if (addopen.value == true) {
            form.value.customerId = selectedId.value;
          } else {
            queryParams.value.customerId = selectedId.value;
          }
        }
      } else {
        if (title.value == "选择销售人员信息") {
          queryParams.value.userId = form.value.id;
        } else {
          queryParams.value.customerId = form.value.id;
        }
      }
      queryopen.value = false;
    }
  });

  resetCheck();
}

/**商品选择的弹出框确认 */
function submitFormProduct() {
  productAddopen.value = false;
  products.value.forEach((element) => {
    if (element.total != 0) {
      // 检查是否已存在具有相同 productId 的条目
      const existingDetail = form.value.orderDetails.find((detail) => {
        detail.productId === element.productId;
        detail.price != element.price;
      });

      if (existingDetail) {
        // 如果存在，增加 total 值
        existingDetail.total += element.total;
      } else {
        // 如果不存在，添加新的条目
        form.value.orderDetails.push({
          productId: element.productId,
          productName: element.productName,
          total: element.total,
          price: element.price,
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const orderId = row.orderId || ids.value;
  proxy.$modal
    .confirm('是否确认删除销售订单为"' + orderId + '"的数据项?')
    .then(function () {
      return delOrder(orderId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
//销售明细单条的商品总价
function totalAmountBycomputer(row) {
  row.totalAmount = row.total * row.price;
  return row.total * row.price;
}
//新增处理
function handleAdd() {
  form.value = {
    customerId: undefined,
    shoppingAddress: undefined,
    orderStatus: 0,
    salespersonId: undefined,
    orderDetails: [],
  };
  addopen.value = true;
  title.title = "新增销售订单";
}

//商品选择弹出控制
function productAdd() {
  productAddopen.value = true;
  title.value = "选择商品信息";
  //发送请求
  handleQueryProduct();
}
//商品查询
function handleQueryProduct() {
  getProducts(queryproduct.value).then((response) => {
    totalP.value = response.data.total;
    products.value = [];
    console.log(response);
    response.data.list.forEach((element) => {
      let form = {
        productId: element.productId,
        productName: element.product.productName,
        brand: element.product.brand,
        description: element.product.description,
        total: 0,
        price: element.unitPurchasePrice,
        inventoryQuantity: element.inventoryQuantity,
        totalAmount: 0,
      };
      products.value.push(form);
    });
    totalPro.value = response.data.total;
    console.log(products.value);
  });
}

//添加订单信息
function submitFormaddOrder() {
  console.log(form.value);
  if (form.value.orderDetails.length != 0) {
    addOrder(form.value).then((response) => {
      console.log(response);
      proxy.$modal.msgSuccess("添加成功");
      addopen.value = false;
      getList();
    });
  } else {
    addopen.value = false;
  }
}

//退货控制
function returnTo(row) {
  returnOpen.value = true;
  returnForm.value.orderId = row.orderId;
  title.value = "添加退货信息";
}

//退货确定
function returnSub() {
  if (returnForm.value.rtvBecause != undefined) {
    addReturn(returnForm.value).then((response) => {
      if (response.meta.status == 210) {
        returnOpen.value = false;
        proxy.$modal.msgSuccess("退货申请成功");
      }
    });
  } else {
    returnOpen.value = false;
  }
}

getList();
</script>
